local ConfigLoader = require("config.loader")
local Settings = require("config.settings")
local config = ConfigLoader.load(Settings.CURRENT_GAME)
local logger = require "utils.logger"
local tslib = require "TSLib"

local M = {}

function M.testBaiduOCR()
    -- 识别区域
    local region = { 775, 732, 806, 774 }
    local testImgPath = userPath() .. "/res/test_ocr.png"
    logger.info("截图路径：" .. testImgPath)

    -- 截图操作
    snapshot(testImgPath, region[1], region[2], region[3], region[4])

    -- OCR 参数配置
    local ocr_params = {
        language_type = "ENG",
        detect_direction = "true",
        ocrType = 1
    }

    -- 调用 OCR 服务
    local code1, access_token = getAccessToken(
        config.BAIDU_OCR.API_KEY,
        config.BAIDU_OCR.SECRET_KEY
    )
    if not code1 then
        logger.error("获取access_token失败", access_token)
        return nil
    end

    local code2, body = baiduAI(access_token, testImgPath, ocr_params)
    logger.info("OCR识别结果:", body)

    if not code2 then
        logger.error("百度AI接口调用失败", body)
        return nil
    end
    -- 处理识别结果

    -- 解析JSON结果
    local data = cjson.decode(body)
    local json_ok = data ~= nil

    if json_ok and data.words_result and #data.words_result > 0 then
        logger.info("OCR识别成功")
        logger.info("识别结果:", data.words_result[1].words)
        local number = tonumber(data.words_result[1].words)
        if number then
            logger.info("成功提取数字：" .. number)
            return number
        end
    else
        logger.error("OCR识别失败 状态码:" .. tostring(data.error_code or '未知') .. " 信息:" .. tostring(data.error_msg or '无'))
    end
    return nil
end

return M
